package cn.iocoder.yudao.module.promotion.gift.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.business.basic.controller.PageController;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.api.shop.info.dto.ShopInfoDTO;
import cn.iocoder.yudao.module.promotion.gift.pojo.dto.AppGiftTakeDTO;
import cn.iocoder.yudao.module.promotion.gift.pojo.dto.AppGiftTransferDTO;
import cn.iocoder.yudao.module.promotion.gift.pojo.dto.GiftRecordQueryDTO;
import cn.iocoder.yudao.module.promotion.gift.pojo.vo.GiftRecordListVO;
import cn.iocoder.yudao.module.promotion.gift.pojo.vo.GiftRecordVO;
import cn.iocoder.yudao.module.promotion.gift.service.app.AppGiftRecordService;
import cn.iocoder.yudao.module.promotion.gift.service.core.CoreGiftRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 APP - 赠品记录")
@RestController
@RequestMapping("/promotion/gift/record")
@Validated
public class AppGiftRecordController implements PageController<GiftRecordVO, GiftRecordQueryDTO> {

    @Resource
    private CoreGiftRecordService coreGiftRecordService;
    @Resource
    private AppGiftRecordService appGiftRecordService;

    @Resource
    private ShopInfoApi shopInfoApi;

    @Operation(summary = "领取赠品")
    @PostMapping("/take")
    public CommonResult<Boolean> take(@Validated @RequestBody AppGiftTakeDTO param) {
        return success(coreGiftRecordService.take(getLoginUserId(), param));
    }

    @Operation(summary = "转赠赠品")
    @PostMapping("/transfer")
    public CommonResult<Boolean> transfer(@Validated @RequestBody AppGiftTransferDTO param) {
        return success(coreGiftRecordService.transfer(getLoginUserId(), param));
    }

    @Override
    public CommonResult<PageResult<GiftRecordVO>> getPage(Integer pageNo, Integer pageSize, GiftRecordQueryDTO param) {
        PageResult<GiftRecordVO> page = coreGiftRecordService.getPage(pageNo, pageSize, param, getLoginUserId());
        return success(page);
    }

    @GetMapping("/page-group")
    @Operation(summary = "分页（按店铺分组）")
    public CommonResult<PageResult<GiftRecordListVO>> getGroupPage(Integer pageNo, Integer pageSize, GiftRecordQueryDTO param) {
        PageResult<GiftRecordVO> page = coreGiftRecordService.getPage(pageNo, pageSize, param, getLoginUserId());
        List<GiftRecordVO> list = page.getList();
        if (CollUtil.isEmpty(list)) {
            return success(PageResult.empty());
        }
        Map<Long, ShopInfoDTO> shops = shopInfoApi.getShopInfoMap(convertSet(list, GiftRecordVO::getShopId));
        // 按店铺分组
        Map<Long, List<GiftRecordVO>> groupByShop = new HashMap<>();
        for (GiftRecordVO it : list) {
            groupByShop.computeIfAbsent(it.getShopId(), k -> new ArrayList<>()).add(it);
        }
        // 转换数据格式
        List<GiftRecordListVO> respVOS = new ArrayList<>();
        for (Map.Entry<Long, List<GiftRecordVO>> entry : groupByShop.entrySet()) {
            GiftRecordListVO respVO = new GiftRecordListVO();
            respVO.setShopId(entry.getKey());
            respVO.setShop(shops.get(entry.getKey()));
            respVO.setItems(entry.getValue());
            respVOS.add(respVO);
        }
        return success(new PageResult<>(respVOS, page.getTotal()));
    }

    @GetMapping("/granted")
    @Parameter(name = "tradeNo", description = "交易单号")
    @Operation(summary = "根据交易单号查询已发放的赠品")
    @PermitAll // 无需登录限制，扫码商家码付款的情况下可能未登录
    public CommonResult<List<GiftRecordVO>> getGrantedAmount(@RequestParam(value = "tradeNo") String tradeNo) {
        return success(appGiftRecordService.getGranted(tradeNo));
    }

}